package org.ssm.demo.schedule;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.ssm.demo.Thread.MyTaskCall;

import java.util.*;
import java.util.concurrent.*;

import static org.ssm.demo.utils.ThreadUtils.getIndex;

/**
 * @Author: Junerain
 * @Description:
 * @Date:Created in 11:05 2018/5/10
 * @Modified By:
 */
public class exportXmlJob extends QuartzJobBean {

    private static int counter = 0;

    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        int minSize = 100;//单个线程最小执行数量
        int maxTaskNum = 5;//最大线程数
        int count = 1000000;//总数
        int[] indexs = getIndex(count,minSize,maxTaskNum);
//        System.out.print("[");
//        for(int i = 0;i<indexs.length;i++){
//            System.out.print(indexs[i]+",");
//        }
//        System.out.println("]");
        int offset = indexs[1] - indexs[0];
        int endIndex = indexs[indexs.length-2];

        Map<Integer,String> map = new HashMap<Integer,String>();
        List<Future<String>> futures = new ArrayList<>();

        //多线程
        long startTime1 = System.currentTimeMillis();
        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
        for(int i=0;i<indexs.length-1;i++){
//            MyTask myTask = new MyTask(indexs[i],offset,endIndex);
//            executor.execute(myTask);
            futures.add(executor.submit(new MyTaskCall(indexs[i],offset,endIndex)));
        }
        executor.shutdown();
        try {//等待直到所有任务完成
            executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long endTime1 = System.currentTimeMillis();
        System.out.println("导出程序运行时间：" + (endTime1 - startTime1) + "ms");//输出程序运行时间

        for (int i = 0;i<futures.size();i++) {
//            System.out.println(">>>" + futures.get(i).get());
            try {
                map.put(i,futures.get(i).get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    }
}
